package com.example.testproj.suspend;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.graphics.PixelFormat;
import android.os.IBinder;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.TextView;

import com.example.testproj.R;

public class SuspendService extends Service implements View.OnClickListener {
    private static final String TAG = "SuspendService";
    private View mSuspendView;
    private WindowManager mWindowManager;

    public SuspendService() {
    }

    @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
        throw new UnsupportedOperationException("Not yet implemented");
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.d(TAG, "onStartCommand: ");
        showWindow();
        return super.onStartCommand(intent, flags, startId);
    }

    private void showWindow() {
        mWindowManager = (WindowManager) getSystemService(WINDOW_SERVICE);
//        Button button=new Button(this);
//        button.setText("这是一个悬浮按钮");
//        button.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                Toast.makeText(SuspendService.this.getApplication(),"点击了悬浮窗按钮",Toast.LENGTH_SHORT).show();
//            }
//        });

        mSuspendView = LayoutInflater.from(this).inflate(R.layout.suspend_view_layout,null,false);

        TextView textView= (TextView) mSuspendView.findViewById(R.id.tv_close_window);
        textView.setOnClickListener(this);

        WindowManager.LayoutParams layoutParams=new WindowManager.LayoutParams(
                dip2px(this.getApplication(),300), ViewGroup.LayoutParams.WRAP_CONTENT,
                0,0,9999,
                WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE, PixelFormat.TRANSPARENT);

        mWindowManager.addView(mSuspendView,layoutParams);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        mWindowManager.removeView(mSuspendView);
        Log.d(TAG, "onDestroy: ");
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.tv_close_window:
                Intent intent=new Intent(this,SuspendService.class);
                stopService(intent);
                break;
        }
    }

    public static int dip2px(Context context, float dpValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }
}
